<template>

    <div class="index-box">
        <div class="cont-box">

            <el-form :model="queryParams" ref="queryForm" :inline="true" class="zdy-form search-form-new"
                label-width="68px" @keyup.enter.native="search">
                <el-form-item label="" prop="deptIdList">
                    <el-select class="bumen" collapse-tags v-model="queryParams.deptIdList" placeholder="部门筛选" multiple clearable>
                        <el-option v-for="dict in allDepts" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="gameId">
                    <el-select v-model="queryParams.gameId" placeholder="选择游戏" clearable filterable>
                        <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="channel">

                    <el-select filterable clearable v-model="queryParams.channel" placeholder="选择回收渠道">
                        <el-option v-for="(item, key) in qudaoList" :key="key" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="saleChannel">
                    <el-select filterable clearable v-model="queryParams.saleChannel" placeholder="选择销售渠道">
                        <el-option v-for="(item, key) in qudaoList" :key="key" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>

                <el-form-item label="" prop="userId">
                    <el-select clearable filterable v-model="queryParams.userId" placeholder="选择员工">
                        <el-option v-for="(item, key) in yuangongList" :key="key" :label="item.nickName"
                            :value="item.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="createId">
                    <div class="flex">
                        <el-date-picker :clearable="false" key="yearSelect" v-if="dateType === 'daterange'"
                            style="width: 300px" v-model="timer" align="right" :type="dateType" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
                            @change="timeSearch" />
                        <el-date-picker :clearable="false" :key="dateType + 'select'" class="search-time" v-else
                            align="right" v-model="timer" :type="dateType"
                            :placeholder="dateType === 'month' ? '选择月份' : '选择日期'" :value-format="dateType === 'month'?'yyyy-MM':'yyyy-MM-dd'"
                            @change="timeSearch" />
                        <div class="select flex">
                            <div class="day1" @click="handleDateType(3)" :class="{ active: types === 3 }">日
                            </div>
                            <div class="day2" @click="handleDateType(2)" :class="{ active: types === 2 }">月
                            </div>
                            <div class="day3" @click="handleDateType(1)" :class="{ active: types === 1 }">自定义
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <div>
                    <el-button type="primary" icon="el-icon-search" @click="searChange">搜索</el-button>
                    <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </div>
            </el-form>
            <div class="tips" v-if="tipShow" >订单数据统计分析时,只统计【交易完成】的订单数据
                <i @click="tipShow = false" class="el-icon-error"></i>
            </div>
            <div class="customTab">
                 <div class="flex flex-box refresh" @click="searChange"> 
                              <span class="font14">刷新</span>
                          <span class="el-icon-refresh-right"></span>              
                </div>
                <el-tabs type="border-card" v-model="actived" v-loading="loading" @tab-click="searChange">
                    <el-tab-pane label="概况" name="order">
                        <div v-if="actived == 'order'">
                        <order ref="orderRef" :formatDateRange="formatDateRange" :queryParams="queryParams"></order>
                        <orderEcharts ref="orderEchartsRef" :formatDateRange="formatDateRange"
                            :queryParams="queryParams"></orderEcharts>
                             </div>
                    </el-tab-pane>
                    <el-tab-pane label="经营明细" name="operate">
                        <div v-if="actived == 'operate'">
                            <operate  ref="operateRef" :formatDateRange="formatDateRange"
                            :queryParams="queryParams"></operate>
                       </div>
                    </el-tab-pane>
                    <el-tab-pane label="利润分布" name="profit">
                        <div v-if="actived == 'profit'">
                            <div class="flex flex-box" style="top:-14px ;">
                                <div class="segmented-control">
                                    <div v-for="item in segmentList" :key="item.value"
                                        :class="['segment', { active: fenbuqarams.groupKey === item.value }]"
                                        @click="selectSegment(item.value)">
                                        {{ item.label }}
                                    </div>
                                </div>
                            </div>
                            <columnar ref="profitRef" :formatDateRange="formatDateRange" :chartData="processedFenbuData.chartData">
                            </columnar>
                            <profit ref="profitTableRef" :activeSegment="fenbuqarams.groupKey" :formatDateRange="formatDateRange" :tableData="processedFenbuData.tableData"></profit>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <!-- <div class="update-timer">更新时间:2025 <span>刷新</span></div> -->
            </div>
        </div>
    </div>
</template>
<script>
import { listDept } from "@/api/system/dept";
import gameListApi from "@/api/gameConfig/gameList";
import otherChannels from "@/api/retrieveManage/otherChannels"
import order from "./components/order.vue"
import operate from "./components/operate.vue"
import orderEcharts from "./components/orderEcharts.vue"
import profit from "./components/profit.vue"
import supplyConfigApi from "@/api/system/supplyConfig";
import columnar from "./components/columnar.vue";
import { fenbu } from "@/api/dmgt/index";

export default {
    name: "Detent",
    components: { order, orderEcharts, operate, profit, columnar },
    data() {
        return {
            isShow:true,
            loading: false,
            actived: 'order',
            queryParams: {
                deptIdList: [],
                gameId: '',
                channel: '',
                saleChannel: '',
                userId: '',
                createTimeStart: '',
                createTimeEnd: ''
            },
            fenbuqarams:{
                 groupKey:'youxi',
            },
            types: 1,
            gameList: [],
            qudaoList: [],
            allUsers: [], //销售渠道
            yuangongList: [],
            tenantList: [],
            timer: [],
            dateType: 'daterange', // 新增，默认自定义
            allDepts: [],
            tipShow: true,

           
               segmentList: [
        { label: '游戏', value: 'youxi' },
        { label: '渠道', value: 'qudao' },
        { label: '销售员工', value: 'xiaoshourenyuan' },
        { label: '被销员工', value: 'beixiaoyuangong'},
        { label: '回收价位', value: 'huishoujiawei' },
        { label: '销售时间', value: 'xiaoshoushijian' }
      ],
      processedFenbuData: {
          chartData: {
              xData: [],
              quantityList: [],
              amountList: [],
              orderCountList: []
          },
          tableData: []
      }
        };
    },
    computed: {
        formatDateRange() {
            // 判断 timer 类型并格式化显示
            if (Array.isArray(this.timer) && this.timer.length === 2) {
                return `${this.timer[0]} ~ ${this.timer[1]}`;
            } else if (typeof this.timer === 'string') {
                return this.timer;
            } else if (Array.isArray(this.timer) && this.timer.length === 1) {
                return this.timer[0];
            }
        }
    },
    created() {
        // 默认一月时间
        // 获取最近三十天的日期范围
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 30);

        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };
        this.queryParams.createTimeStart = formatDate(startDate);
        this.queryParams.createTimeEnd = formatDate(endDate) + ' ' + '23:59:59';
        this.timer = [formatDate(startDate), formatDate(endDate)];
        this.handleDateType(1);
        this.getGameList();
        this.getQudaoList()
        this.getYuangongList();
        this.getDeptList()

    },

    methods: {
          selectSegment(val) {
            this.fenbuqarams.groupKey = val;
             this.$nextTick(() => {
                    this.getFenbu()
                });
    },
        // 查询部门列表
        async getDeptList() {
            try {
                const { data } = await listDept()
                this.allDepts = data.filter(r => r.parentId != 100)
            } catch (error) {

            }
        },
        getGameList() {
            gameListApi.getGameList().then((res) => {
                this.gameList = res.rows;
            });
        },
        getQudaoList() {
            otherChannels.getQudaoList({
                isPage: 2,
                type: 2,
                pageNum: 1,
                pageSize: 100
            }).then((response) => {
                this.qudaoList = response.rows;
            });
        },
        // 获取所有员工列表
        getYuangongList() {
            supplyConfigApi
                .getAllUserList({
                    userNewType: 1,
                })
                .then((res) => {
                    this.yuangongList = res.rows;
                });
        },
        searChange() {
            if (this.$refs.orderRef && this.actived == 'order') {
                this.$refs.orderRef.init();
                this.$refs.orderEchartsRef.getQushi();
            }
            if (this.$refs.operateRef && this.actived == 'operate') {
                this.$refs.operateRef.init();
            }
            if (this.actived == 'profit') {
                // 确保在切换到利润分布时清理之前的图表实例
                this.$nextTick(() => {
                    this.getFenbu()
                });
            }
        },
        // 数据处理方法 - 统一处理不同 groupKey 的数据格式
        processFenbuData(rawData, groupKey) {
            const chartData = {
                xData: [],
                quantityList: [],
                amountList: [],
                orderCountList: []
            };
            const tableData = [];

            switch (groupKey) {
                case 'youxi':
                    // 游戏数据: [{groupName: "虞都互联测试", saleCot: 1, avg: 55, saleprofits: 55}]
                    rawData.forEach(item => {
                        chartData.xData.push(item.gameName);
                        chartData.quantityList.push(item.saleprofits);
                        chartData.amountList.push(item.avg);
                        chartData.orderCountList.push(item.saleCot);
                        tableData.push({
                            gameName: item.gameName,
                            saleprofits: item.saleprofits,
                            avg: item.avg,
                            saleCot: item.saleCot
                        });
                    });
                    break;

                case 'xiaoshourenyuan':
                    // 销售员工数据: [{saleCot: 1, avg: 55, saleprofits: 55, yuangongName: "未知"}]
                    rawData.forEach(item => {
                        chartData.xData.push(item.yuangongName);
                        chartData.quantityList.push(item.saleprofits);
                        chartData.amountList.push(item.avg);
                        chartData.orderCountList.push(item.saleCot);
                        tableData.push({
                            yuangongName: item.yuangongName,
                            saleprofits: item.saleprofits,
                            avg: item.avg,
                            saleCot: item.saleCot
                        });
                    });
                    break;

                case 'beixiaoyuangong':
                    // 被销员工数据: [{saleCot: 1, avg: 55, saleprofits: 55, yuangongName: "麦麦号-白泽网游"}]
                    rawData.forEach(item => {
                        chartData.xData.push(item.yuangongName);
                        chartData.quantityList.push(item.saleprofits);
                        chartData.amountList.push(item.avg);
                        chartData.orderCountList.push(item.saleCot);
                        tableData.push({
                            yuangongName: item.yuangongName,
                            saleprofits: item.saleprofits,
                            avg: item.avg,
                            saleCot: item.saleCot
                        });
                    });
                    break;

                case 'huishoujiawei':
                    // 回收价位数据: {250-500: {saleCot: 0, avg: 0, saleprofits: 0}}
                    // 定义回收价位的排序顺序
                    const huishouOrder = [
                        'xiaoyu250',
                        '250-500', 
                        '500-1000',
                        '1000-2000',
                        '2000-5000',
                        '5000-10000',
                        '10000yishang',
                        'qita'
                    ];
                    
                    // 按照预定义顺序处理数据
                    huishouOrder.forEach(key => {
                        if (rawData[key]) {
                            let name = ''
                            if(key == 'xiaoyu250') {
                                name = '小于250'
                            }else if(key =='qita') {
                                name = '其他'
                            }else if(key == '10000yishang') {
                                name = '10000以上'
                            }
                            else {
                                name = key
                            }
                            const item = rawData[key];
                            chartData.xData.push(name);
                            chartData.quantityList.push(item.saleprofits);
                            chartData.amountList.push(item.avg);
                            chartData.orderCountList.push(item.saleCot);
                            tableData.push({
                                yuangongName: name,
                                saleprofits: item.saleprofits,
                                avg: item.avg,
                                saleCot: item.saleCot
                            });
                        }
                    });
                    break;

                case 'xiaoshoushijian':
                    // 销售时间数据: {2025-07-05: {saleCot: 0, avg: 0, saleprofits: 0}}
                    Object.keys(rawData).forEach(key => {
                        const item = rawData[key];
                        chartData.xData.push(key);
                        chartData.quantityList.push(item.saleprofits);
                        chartData.amountList.push(item.avg);
                        chartData.orderCountList.push(item.saleCot);
                        tableData.push({
                            yuangongName: key,
                            saleprofits: item.saleprofits,
                            avg: item.avg,
                            saleCot: item.saleCot
                        });
                    });
                    break;

                case 'qudao':
                    // 渠道数据: 假设与游戏数据格式相同
                    rawData.forEach(item => {
                        chartData.xData.push(item.groupName);
                        chartData.quantityList.push(item.saleprofits);
                        chartData.amountList.push(item.avg);
                        chartData.orderCountList.push(item.saleCot);
                        tableData.push({
                            groupName: item.groupName,
                            saleprofits: item.saleprofits,
                            avg: item.avg,
                            saleCot: item.saleCot
                        });
                    });
                    break;

                default:
                    console.warn('未知的 groupKey:', groupKey);
                    break;
            }

            return { chartData, tableData };
        },

        async getFenbu() {
            try {
                this.loading = true;
                let groupKey = this.fenbuqarams.groupKey;
                this.fenbuqarams = { ...this.fenbuqarams ,...this.queryParams };
                this.fenbuqarams.groupKey = groupKey;
                const res = await fenbu(this.fenbuqarams);
                
                if (res.code === 200 && res.data) {
                    // 处理数据
                    const processedData = this.processFenbuData(res.data, this.fenbuqarams.groupKey);
                    this.processedFenbuData = processedData;
                    
                    // 通知子组件更新数据
                    this.$nextTick(() => {
                        if (this.$refs.profitRef) {
                            this.$refs.profitRef.updateChartData(processedData.chartData);
                        }
                        if (this.$refs.profitTableRef) {
                            this.$refs.profitTableRef.updateTableData(processedData.tableData);
                        }
                    });
                } else {
                    // 如果没有数据，清空图表
                    this.processedFenbuData = {
                        chartData: {
                            xData: [],
                            quantityList: [],
                            amountList: [],
                            orderCountList: []
                        },
                        tableData: []
                    };
                    
                    // 通知子组件清空数据
                    this.$nextTick(() => {
                        if (this.$refs.profitRef) {
                            this.$refs.profitRef.updateChartData(this.processedFenbuData.chartData);
                        }
                        if (this.$refs.profitTableRef) {
                            this.$refs.profitTableRef.updateTableData(this.processedFenbuData.tableData);
                        }
                    });
                }
            } catch (error) {
                console.error('获取分布数据失败:', error);
                this.$message.error('获取数据失败');
                
                // 出错时也清空数据
                this.processedFenbuData = {
                    chartData: {
                        xData: [],
                        quantityList: [],
                        amountList: [],
                        orderCountList: []
                    },
                    tableData: []
                };
            } finally {
                this.loading = false;
            }
        },

        timeSearch(val) {
            if (!val) return;
            if (this.types == 1) { //代表是自定义
                this.queryParams.createTimeStart = val[0] ? val[0] : '';
                this.queryParams.createTimeEnd = val[1] ? val[1] + ' 23:59:59' : '';
            }
            if (this.types == 2) { //代表是月 从1号到月末
                // 获取当月第一天
                const [year, month] = val.split('-');
                // 当月第一天
                this.queryParams.createTimeStart = `${year}-${month}-01`;
                // 当月最后一天
                const lastDay = new Date(year, month, 0); // 月份是 1-12，但 Date 中 month 是 0-11
                this.queryParams.createTimeEnd = `${year}-${month}-${lastDay.getDate()} 23:59:59`;
            }
            if (this.types == 3) { //代表是日
                this.queryParams.createTimeStart = val + ' 00:00:00';
                this.queryParams.createTimeEnd = val + ' 23:59:59';
            }
        },
        resetQuery() {
            this.$refs.queryForm.resetFields();
            this.types = 1;
              //利润分布明细表
            this.fenbuqarams.groupKey = 'youxi'
           this.handleDateType(this.types)
        },
        handleDateType(type) {
            this.types = type;
            // 获取当前日期
            const now = new Date();
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            if (type === 3) {
                // 日：默认当天
                this.dateType = 'date';
                const today = formatDate(now);
                this.timer = today;
                this.queryParams.createTimeStart = today + ' 00:00:00';
                this.queryParams.createTimeEnd = today + ' 23:59:59';
            } else if (type === 2) {
                // 月：默认当月
                this.dateType = 'month';
                const currentMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
                this.timer = currentMonth;

                // 当月第一天
                this.queryParams.createTimeStart = `${currentMonth}-01`;
                // 当月最后一天
                const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
                this.queryParams.createTimeEnd = `${currentMonth}-${lastDay.getDate()} 23:59:59`;
            } else {
                // 自定义：默认一个月的时间范围
                this.dateType = 'daterange';
                const endDate = now;
                const startDate = new Date();
                startDate.setDate(startDate.getDate() - 30);

                const startDateStr = formatDate(startDate);
                const endDateStr = formatDate(endDate);

                this.timer = [startDateStr, endDateStr];
                this.queryParams.createTimeStart = startDateStr;
                this.queryParams.createTimeEnd = endDateStr + ' 23:59:59';
            }
            this.searChange()
        }
    },
    mounted() {

    }
}


</script>
<style scoped lang="scss">
.zdy-form {
    padding: 10px;
}

.select {
    align-items: center;
    margin-left: 6px;

    >div {
        border: 1px solid #ccc;
        border-right: none;
        padding: 0 20px;
        height: 27px;
        line-height: 27px;
        cursor: pointer;
        color: #4E5969;
        font-size: 14px;

        &:last-child {
            border-right: 1px solid #D8DCE6;
            border-radius: 0 3px 3px 0;
        }

        &:first-child {
            border-radius: 3px 0 0 3px;
        }

        &.active {
            border-color: #6C5DD3;
            background: #6C5DD3;
            color: #fff;
        }
    }
}

.tips {
    display: flex;
    justify-content: space-between;
    color: #fff;
    background: #494994;
    border-radius: 8px;
    padding: 10px;
    margin: 16px 0;

    i {
        cursor: pointer;
        font-size: 16px;
        color: rgba(255, 255, 255, 0.5);
    }
}

.flex {
    position: relative;
}

.search-time {
    ::v-deep .el-input__inner {
        text-align: center;
    }
}

.customTab {
    margin-top: 14px;
    position: relative;
    padding-bottom: 16px;
    .update-timer {
        position: absolute;
        top: 10px;
        right: 16px;
        font-size: 12px;

        span {
            color: #6C5DD3;
        }
    }

    .tabs-box {
        width: 88%;
        margin: 30px auto;
        justify-content: space-between;
        flex-wrap: wrap;
    }

    .table_box {
        padding: 0 !important;
    }

    ::v-deep .el-tabs--border-card>.el-tabs__content {
        padding: 0 !important;
        overflow: visible !important;
    }

    .tabs-img {
        width: 48px;
        height: 48px;
        margin-right: 8px;

        img {
            width: 100%;
            height: 100%
        }
    }

    .tabs-text {
        color: #333;
        font-size: 15px;
        font-weight: 600;

        .tabs-num {
            margin-top: 4px;
            font-size: 22px;
        }
    }

    ::v-deep {
        .el-tabs--border-card {
            box-shadow: none;
            border: none;
        }

        .el-tabs__item {
            color: #666;
            font-weight: 500;
        }
    }

    ::v-deep .is-active {
        border-radius: 8px 8px 0px 0px;
        border: none;
    }
}

// .el-tabs--card {
//   height: calc(100vh - 110px);
//   /* overflow-y: auto; */
// }
// .el-tab-pane {
//   height: calc(100vh - 110px);
//   overflow-y: auto;
// }
.flex-box {
    margin: 16px 0 0 16px;
    position: absolute;
    right: 16px;
    top: -6px;
    cursor: pointer;
    z-index: 2;
}
 .refresh {
    color: #FA6400;
    font-size: 12px;
    margin-left: 8px;
    font-weight: 400;

    .font14 {
      font-size: 12px;
      margin-right: 4px;
    }

    .el-icon-refresh-right {
      font-size: 15px;
      cursor: pointer;
    }
  }
.app-container {
       overflow: visible !important;
}
</style>